import { ActionContext } from "vuex";
import { RootState } from "../types";
import { UserActionTypes } from "./action-types";
import { MutationTypes } from "./mutation-types";
import { UserInfo } from "./types";
import { authToken } from "/@/api/user/user";
import router from "/@/router";

export type Actions<S = RootState, R = RootState> = {
  [UserActionTypes.User_Auth_Token]({}: ActionContext<S, R>, data: UserInfo): Promise<void>;
  [UserActionTypes.User_Clear_Info]({}: ActionContext<S, R>): Promise<void>;
  [UserActionTypes.User_Exit]({}: ActionContext<S, R>): Promise<void>;
};

export const userActions: Actions = {
  async [UserActionTypes.User_Auth_Token]({ commit }) {
    try {
      const { data } = await authToken();
      if (data) {
        commit(MutationTypes.SET_USER_INFO, data);
      }
    } catch {}
  },
  async [UserActionTypes.User_Clear_Info]({ commit }) {
    commit(MutationTypes.CLEAR_USER_INFO);
  },
  async [UserActionTypes.User_Exit]({ commit }) {
    commit(MutationTypes.CLEAR_USER_INFO);
    router.push("/login");
  },
};
